import React, { useEffect, useRef, useState } from 'react'
import * as echarts from 'echarts'
import { useSelector } from 'react-redux'
function CakeData(props) {
  const chartRef = useRef()
  // 类别1
  let leiBieOne = ['早餐', '电子', '衣物', '其他']

  if (props.bing === 'two') {
    leiBieOne = ['工资', '理财', '其他']
  }
  // 处理支出数据
  let zhiChu = useSelector((item) => {
    let data = [{ z: 0 }, { d: 0 }, { y: 0 }, { q: 0 }]
    item.BillDatax.map((item) => {
      if (item.sort === '早餐') {
        data[0].z = data[0].z + item.money
      } else if (item.sort === '电子') {
        data[1].d = data[1].d + item.money
      } else if (item.sort === '衣物') {
        data[2].y = data[2].y + item.money
      } else if (item.sort === '其他') {
        if (item.money < 0) {
          data[3].q = data[3].q + item.money
        }
      }
    })
    let zhiChuX = [data[0].z, data[1].d, data[2].y, data[3].q]
    return zhiChuX
  })

  // 处理收入数据
  let shouRu = useSelector((item) => {
    let data = [{ z: 0 }, { d: 0 }, { y: 0 }]
    item.BillDatax.map((item) => {
      if (item.sort === '工资') {
        data[0].z = data[0].z + item.money
      } else if (item.sort === '理财') {
        data[1].d = data[1].d + item.money
      } else if (item.sort === '其他') {
        if (item.money > 0) {
          data[2].y = data[2].y + item.money
        }
      }
    })
    let shouRuX = [data[0].z, data[1].d, data[2].y]
    return shouRuX
  })

  // 查看数据
  // console.log('支出：', zhiChu)
  // console.log('收入:', shouRu)
  const [cakeArray, setCakeArray] = useState([])
  const options = {
    title: {
      text: props.bing === 'two' ? '收入' : '支出',
      top: 'center',
      left: 'center',
    },
    ltip: {
      trigger: 'item',
    },
    legend: {
      top: '5%',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    encode: {
      itemName: 'product',
      value: '2013',
    },
    series: [
      {
        name: props.bing === 'two' ? '收入' : '支出',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },

        labelLine: {
          show: false,
        },
        data: leiBieOne.map((item, index) => {
          return {
            // value: -zhiChu[index],
            value: props.bing === 'two' ? shouRu[index] : -zhiChu[index],
            name: item,
          }
        }),
      },
    ],
  }

  useEffect(() => {
    // 创建一个echarts实例，返回echarts实例。不能在单个容器中创建多个echarts实例
    const chart = echarts.init(chartRef.current)

    // 设置图表实例的配置项和数据
    chart.setOption(options)

    // 组件卸载
    return () => {
      // myChart.dispose() 销毁实例。实例销毁后无法再被使用
      chart.dispose()
    }
  }, [])
  return (
    <div
      style={{
        width: '20vw',
        height: '200px',
        margin: '0 0 0 8vw',
        float: 'left',
      }}
      ref={chartRef}></div>
  )
}
export default CakeData
